import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from '@/router/index'
// 定义白名单，在未登录的时候也可以访问
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 判断是否有token
  const token = store.state.user.token
  // 如果有token：如果去登录页，强行跳转到首页，不是登录页就放行
  if (token) {
    // 如果用户信息存在，就不要再发请求了
    const userId = store.getters.userId
    if (!userId) {
      // token存在时才能获取用户信息  必须加await 当用户进入首页时已经拿到数据了
      await store.dispatch('user/getUserInfo')
      // 动态路由可以通过地址访问，但是没有菜单

      // 筛选路由,通过filter过滤用户的menulist中存在全部动态路由的
      // menulist是用户可以访问的
      const menulist = await store.dispatch('user/getUserInfo')
      const filterMenu = asyncRoutes.filter(item => {
        const name = item.children[0].name
        return menulist.includes(name)
      })
      // router.addRoutes(asyncRoutes)
      // 加入动态路由列表
      filterMenu.push({ path: '*', redirect: '/404', hidden: true })
      router.addRoutes(filterMenu)
      // 存进vuex中
      // store.commit('menu/menus', asyncRoutes)
      store.commit('menu/menus', filterMenu)
      // 解决刷新出现的白屏bug
      next({
        ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
        replace: true // 重进一次, 不保留重复历史
      })
    }
    // 去登录页
    if (to.path === '/login') {
      next('/')
      // 关闭进度条
      NProgress.done()
    } else {
      next()
    }
  } else {
    // 没有token 如果去白名单就放行，别的页面就强行跳转到登录页
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      // 关闭进度条
      NProgress.done()
    }
  }
})
// 全局后置守卫
router.afterEach((to, from, next) => {
  // 关闭进度条
  NProgress.done()
  document.title = getPageTitle(to.meta.title)
  // console.log(to)
})
/* import { Message } from 'element-ui'

import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')

          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
 */
